package GUILayer;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.DefaultTableModel;

import ControlLayer.PersonCtr;
import ModelLayer.Employee;

public class EmployeeGUI extends JPanel implements ActionListener {
	private static final long serialVersionUID = 1L;
	private PersonCtr personCtr;
	private DefaultTableModel employeeTableModel;
	private JScrollPane employeeTableScrollPane;
	private JPanel showAllEmployeePanel;
	private JTable showAllEmployeeTable;
	private JPanel employeeInfoPanel;
	private JPanel choicePanel;

	private JTextField textField_employeeId;
	private JTextField txt_Search;
	private JTextField textField_fname;
	private JTextField textField_address;
	private JTextField textField_country;
	private JTextField textField_lname;
	private JTextField textField_phone;
	private JTextField textField_email;
	private JComboBox<String> jcbPosition;
	private JTextField textField_ssn;
	private JTextField textField_logId;
	private JTextField textField_password;

	private JButton btnSave;
	private JButton btnCreate;

	private JButton btnCancel;
	private JButton btnDelete;

	private String[] listStrings = { "Manager", "Receptionist", "Instructor",
			"" };

	public EmployeeGUI() {
		personCtr = new PersonCtr();
		initialize();
	}

	public void initialize() {
		this.setLayout(new BorderLayout());

		showAllEmployeePanel = new JPanel();
		this.add(showAllEmployeePanel, BorderLayout.CENTER);
		showAllEmployeePanel.setBorder(BorderFactory
				.createTitledBorder("Employees Info"));
		showAllEmployeePanel.setLayout(new BorderLayout());

		txt_Search = new JTextField();
		txt_Search.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				showAllEmployees();
			}
		});
		txt_Search.setColumns(10);

		JPanel searchPanel = new JPanel();
		showAllEmployeePanel.add(searchPanel, BorderLayout.NORTH);
		GroupLayout gl_searchPanel = new GroupLayout(searchPanel);
		gl_searchPanel.setHorizontalGroup(gl_searchPanel.createParallelGroup(
				Alignment.LEADING).addComponent(txt_Search));
		gl_searchPanel.setVerticalGroup(gl_searchPanel.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_searchPanel
						.createSequentialGroup()
						.addGap(5)
						.addComponent(txt_Search, GroupLayout.PREFERRED_SIZE,
								GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE)));
		searchPanel.setLayout(gl_searchPanel);

		// show customer info view
		JPanel showCusotmerPanel = new JPanel();
		this.add(showCusotmerPanel, BorderLayout.EAST);
		showCusotmerPanel.setLayout(new BorderLayout());
		showCusotmerPanel.setBorder(BorderFactory.createTitledBorder("Info"));

		employeeInfoPanel = new JPanel();
		JLabel lblemployeeId = new JLabel("Employee Id: ");
		JLabel lblfname = new JLabel("First Name: ");
		JLabel lbladdress = new JLabel("Address: ");
		JLabel lblCountry = new JLabel("Country: ");
		JLabel lblEmail = new JLabel("Email: ");
		JLabel lblPhone = new JLabel("Phone: ");
		JLabel lblPosition = new JLabel("Position: ");
		JLabel lblSsn = new JLabel("Ssn: ");
		JLabel lblLname = new JLabel("Last Name: ");
		JLabel lbllogId = new JLabel("Log Id: ");
		JLabel lblpassword = new JLabel("Pass Word: ");

		textField_logId = new JTextField();
		textField_password = new JTextField();
		textField_employeeId = new JTextField();
		textField_employeeId.setEditable(false); // Id is not able changed
		textField_logId.setEditable(false);
		textField_password.setEditable(false);

		textField_fname = new JTextField();
		textField_address = new JTextField();
		textField_country = new JTextField();
		textField_lname = new JTextField();
		textField_phone = new JTextField();
		textField_email = new JTextField();
		textField_ssn = new JTextField();

		jcbPosition = new JComboBox<String>(listStrings);
		jcbPosition.setSelectedIndex(3);
		jcbPosition.addActionListener(this);

		GroupLayout gl = new GroupLayout(employeeInfoPanel);
		employeeInfoPanel.setLayout(gl);
		employeeInfoPanel.setBorder(BorderFactory
				.createTitledBorder("Employee"));
		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

		gl.setHorizontalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblemployeeId)
								.addComponent(lblfname).addComponent(lblLname)
								.addComponent(lblSsn).addComponent(lbladdress)
								.addComponent(lblCountry)
								.addComponent(lblPhone).addComponent(lblEmail)
								.addComponent(lblPosition)
								.addComponent(lbllogId)
								.addComponent(lblpassword))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(textField_employeeId)
								.addComponent(textField_fname)
								.addComponent(textField_lname)
								.addComponent(textField_ssn)
								.addComponent(textField_address)
								.addComponent(textField_country)
								.addComponent(textField_phone)
								.addComponent(textField_email)
								.addComponent(jcbPosition)
								.addComponent(textField_logId)
								.addComponent(textField_password)));
		gl.setVerticalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblemployeeId)
								.addComponent(textField_employeeId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblfname)
								.addComponent(textField_fname))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblLname)
								.addComponent(textField_lname))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblSsn)
								.addComponent(textField_ssn))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lbladdress)
								.addComponent(textField_address))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblCountry)
								.addComponent(textField_country))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblPhone)
								.addComponent(textField_phone))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblEmail)
								.addComponent(textField_email))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblPosition)
								.addComponent(jcbPosition))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lbllogId)
								.addComponent(textField_logId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblpassword)
								.addComponent(textField_password)));

		showCusotmerPanel.add(employeeInfoPanel, BorderLayout.NORTH);

		choicePanel = new JPanel();
		choicePanel.setLayout(new FlowLayout());
		btnCreate = new JButton("Create");

		btnDelete = new JButton("Delete");
		btnSave = new JButton("Save");
		btnCancel = new JButton("Clear");

		choicePanel.add(btnCreate);

		choicePanel.add(btnSave);
		choicePanel.add(btnDelete);
		choicePanel.add(btnCancel);
		showCusotmerPanel.add(choicePanel, BorderLayout.CENTER);

		addEmployeesTable();
		showAllEmployees();

		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!textField_employeeId.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null,
							"Please clear employee field before creating one",
							"Error", JOptionPane.ERROR_MESSAGE);
				} else {
					try {
						personCtr.createEmployee(textField_fname.getText(),
								textField_lname.getText(),
								textField_address.getText(),
								textField_country.getText(),
								textField_phone.getText(),
								textField_email.getText(), "Employee",
								textField_ssn.getText(),
								listStrings[jcbPosition.getSelectedIndex()]);
						JOptionPane.showMessageDialog(null,
								"The employee is created", "Create Employee",
								JOptionPane.INFORMATION_MESSAGE);
					} catch (Exception ex) {
						JOptionPane.showMessageDialog(null,
								"Please input correct values", "Error",
								JOptionPane.ERROR_MESSAGE);
					}
					cleanTextField();
					showAllEmployees();
				}
			}
		});

		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (textField_employeeId.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null,
							"Please select an employee", "Error",
							JOptionPane.ERROR_MESSAGE);
				} else {
					int reply = JOptionPane.showConfirmDialog(null,
							"Do you want to delete this employee ?",
							"Delete Customer", JOptionPane.YES_NO_OPTION,
							JOptionPane.WARNING_MESSAGE);
					if (reply == JOptionPane.YES_OPTION) {
						try {
							personCtr.deleteEmployee(Integer
									.parseInt(textField_employeeId.getText()));
							JOptionPane.showMessageDialog(null,
									"The employe is deleted", "Delete Guest",
									JOptionPane.INFORMATION_MESSAGE);
							cleanTextField();
							showAllEmployees();
						} catch (Exception e1) {
						}
					}
				}
			}
		});

		btnSave.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				if (textField_employeeId.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null,
							"Please select an employee", "Error",
							JOptionPane.ERROR_MESSAGE);
				} else {
					try {
						String position = getPositionType();
						int auth;
						if (position.equals("Manager")) {
							auth = 2;
						} else if (position.equals("Receptionist")) {
							auth = 3;
						} else {
							auth = 4;
						}
						personCtr.updateEmployee(Integer
								.parseInt(textField_employeeId.getText()),
								textField_fname.getText(), textField_lname
										.getText(),
								textField_address.getText(), textField_country
										.getText(), textField_phone.getText(),
								textField_email.getText(), auth, textField_ssn
										.getText(), position);
						JOptionPane.showMessageDialog(null,
								"The employee info is saved",
								"Update Employee",
								JOptionPane.INFORMATION_MESSAGE);
					} catch (Exception a) {
						JOptionPane.showMessageDialog(null,
								"Please input correct values", "Error",
								JOptionPane.ERROR_MESSAGE);
					}
					cleanTextField();
					showAllEmployees();
				}
			}
		});

		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cleanTextField();
			}
		});

	}

	public void actionPerformed(ActionEvent e) {
		// JComboBox cb = (JComboBox) e.getSource();
		// String list = (String) cb.getSelectedItem();
	}

	public void addEmployeesTable() {
		employeeTableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		employeeTableModel.addColumn("ID");
		employeeTableModel.addColumn("First Name");
		employeeTableModel.addColumn("Last Name");
		employeeTableModel.addColumn("Ssn");
		employeeTableModel.addColumn("Address");
		employeeTableModel.addColumn("Country");
		employeeTableModel.addColumn("Phone");
		employeeTableModel.addColumn("Email");
		employeeTableModel.addColumn("Position");

		employeeTableScrollPane = new JScrollPane();

		showAllEmployeePanel.add(employeeTableScrollPane, BorderLayout.CENTER);

		showAllEmployeeTable = new JTable(employeeTableModel);
		showAllEmployeeTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		showAllEmployeeTable.setAutoCreateRowSorter(true);

		showAllEmployeeTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				int row = showAllEmployeeTable.rowAtPoint(e.getPoint());
				showEmployee(Integer.valueOf((Integer) showAllEmployeeTable
						.getValueAt(row, 0)));
			}
		});
		employeeTableScrollPane.setViewportView(showAllEmployeeTable);
	}

	public void showAllEmployees() {

		String searchFilter = txt_Search.getText();

		ArrayList<Employee> employees = personCtr.getAllEmployee();
		employeeTableModel.setRowCount(0);
		for (Employee employee : employees) {
			if (((Integer) employee.getID()).toString().toLowerCase()
					.contains(searchFilter.toLowerCase())
					|| employee.getfName().toLowerCase()
							.contains(searchFilter.toLowerCase())
					|| employee.getlName().toLowerCase()
							.contains(searchFilter.toLowerCase())
					|| employee.getEmail().toLowerCase()
							.contains(searchFilter.toLowerCase())
					|| employee.getPosition().toString().toLowerCase()
							.contains(searchFilter.toLowerCase()))
				try {
					employeeTableModel.addRow(new Object[] { employee.getID(),
							employee.getfName(), employee.getlName(),
							employee.getSsn(), employee.getAddress(),
							employee.getCountry(), employee.getPhone(),
							employee.getEmail(),
							employee.getPosition().toString(), });
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null, e, "Error",
							JOptionPane.ERROR_MESSAGE);
				}
		}

	}

	public boolean showEmployee(int employeeId) {
		boolean success = true;
		Employee employee = null;
		try {
			if (employeeId != 0) {
				employee = (Employee) personCtr.getPerson(employeeId);
			}
		} catch (Exception e) {
			success = false;
			JOptionPane.showMessageDialog(null, e, "Error",
					JOptionPane.ERROR_MESSAGE);
			return success;
		}

		if (success) {
			textField_employeeId.setText(Integer.toString(employee.getID()));
			textField_fname.setText(employee.getfName());
			textField_address.setText(employee.getAddress());
			textField_country.setText(employee.getCountry());
			textField_lname.setText(employee.getlName());
			textField_phone.setText(employee.getPhone());
			selectPosition(employee.getPosition().toString());
			textField_ssn.setText(employee.getSsn());
			textField_email.setText(employee.getEmail());
			textField_logId.setText(employee.getLogId());
			textField_password.setText(employee.getPassword());
		}
		return success;
	}

	public int getTextFieldId(JTextField textField) {
		int id = 0;
		try {
			id = Integer.parseInt(textField.getText());
		} catch (NumberFormatException e) {
			JOptionPane.showMessageDialog(null, "Please input number", "Error",
					JOptionPane.ERROR_MESSAGE);
		} finally {
			textField.setText("");
		}
		return id;
	}

	public void cleanTextField() {
		txt_Search.setText("");
		textField_employeeId.setText("");
		textField_fname.setText("");
		textField_address.setText("");
		textField_country.setText("");
		textField_lname.setText("");
		textField_phone.setText("");
		jcbPosition.setSelectedIndex(3);
		textField_ssn.setText("");
		textField_email.setText("");
		textField_logId.setText("");
		textField_password.setText("");
	}

	public String getPositionType() {
		String position = listStrings[jcbPosition.getSelectedIndex()];
		return position;
	}

	public void selectPosition(String type) {
		if (type.equals("Manager")) {
			jcbPosition.setSelectedIndex(0);
		} else if (type.equals("Receptionist")) {
			jcbPosition.setSelectedIndex(1);
		} else {
			jcbPosition.setSelectedIndex(2);
		}
	}
}
